<template>
  <view class="photo-view">
    <u-navbar
      :title="type ? $t('friend.Paid') : $t('dating.PicAndVideo')"
      @leftClick="leftClick"
      bgColor="#F6F6F6"
      titleStyle="color: #000000"
      placeholder
    >
    </u-navbar>
    <view class="label">
      <view class="first">{{ $t("friend.cover") }}</view>
      <view class="number">({{ fileNum }}/9)</view>
    </view>
    <view class="limit"
      >{{ $t("friend.photoLimit") }} <span class="Mb">5Mb</span>,
      {{ $t("friend.videoLimit") }}<span class="Mb">10Mb</span></view
    >
    <view class="img-photo">
      <view v-for="(t, i) in 9" :key="i" class="add">
        <u-icon
          name="close-circle-fill"
          color="#ff6701"
          size="20"
          class="icon"
          v-if="getfileList(t)"
          @click="clearFile(t)"
        ></u-icon>
        <image
          v-if="getfileList(t) && getfileList(t).type == 'image'"
          :src="getfileList(t).compressImage"
          @click="showPreview(getfileList(t).url)"
          style="width: 214upx; height: 214upx; border-radius: 15rpx"
          mode="aspectFill"
        ></image>
        <j-video
          v-else-if="getfileList(t) && getfileList(t).type == 'video'"
          play-btn-position="center"
          :danmu-btn="true"
          :controls="false"
          :url="getfileList(t).url"
          :poster="getfileList(t).oneUrl"
          :width="'214upx'"
          :height="'214upx'"
          style="width: 214upx; height: 214upx; border-radius: 15rpx"
        />
        <image
          v-else
          @click="onTypePop(t)"
          src="@/static/image/friend/add.png"
          style="width: 214upx; height: 214upx"
        ></image>
      </view>
    </view>

    <view v-if="type" class="price-view">
      <view class="content-detail">
        <view>{{ $t("friend.Currency") }}</view>
        <view class="detail">
          <input
            :placeholder="$t('order.Please-Choose')"
            v-model="receiptCurrency"
            class="input-view"
            disabled
            @tap="handleOpenPicker"
            placeholder-style="color: #A6A6A6;"
          />
          <view class="iconfont icon-jiantou-you arrow-icon"></view>
        </view>
      </view>
      <view class="content-detail">
        <view>{{ $t("friend.setPrice") }}</view>
        <view class="detail">
          <input
            placeholder="0.00"
            v-model="setPrice"
            class="input-view"
            placeholder-style="color: #A6A6A6;"
          />
          <view class="danwei">{{ receiptCurrency }}</view>
        </view>
      </view>
    </view>
    <view class="explain" v-if="type">
      <view>{{ $t("dating.payPicTextFrist") }}
        <span class="money">{{ chatUnit.length ? chatUnit[0].symbol : "" }}{{ setPrice }}</span>
        {{$t("dating.payPicTextMiddle")}}
      </view>
      <view style="margin-top: 20upx"
        >{{ $t("dating.payPicTextLast") }} <span class="money">{{ picFee }}% </span></view
      >
    </view>
    <view class="btn" @click="postHandle">{{ $t("friend.post") }}</view>

    <SelectPopup
    v-if="show"
      :title="$t('order.currency')"
      :show.sync="show"
      :option="currencyList"
      @finish="confirm"
      @cancel="close"
      :value="selectReceiptCurrency[0].id"
      labelSigned="currency"
      valueSigned="id"
      :cancelText="$t('cancel')"
      :confirmText="$t('confirm')"
    ></SelectPopup>

    <SelectPop
      :show.sync="SelectPopupShow"
      :option="typeOption"
      :value="applicationLocale"
      @finish="onSelectType"
      v-if="SelectPopupShow"
      labelSigned="text"
      valueSigned="code"
    ></SelectPop>
  </view>
</template>

<script>
import SelectPopup from "@/components/SelectPopup.vue";
import SelectPop from "pagesDiscover/friendsInformation/components/SelectPop";
import { getCurrencyList } from "@/services/bourse.js";
import { friendInfoAdd, updateFriendInfo, queryFeePercent } from "@/services/makeFriend";
import config from "@/config/app.config";
import store from "@/store/index";
import { getSymbol } from "@/utils/index";
import {
	getWalletList
} from '@/services/user.js'
export default {
  components: {
    SelectPop,
    SelectPopup
  },
  data() {
    return {
      chatUnit: "",
      SelectPopupShow: false,
      typeOption: [
        {
          text: this.$t('dating.selectFromPhoto'),
          code: "image",
        },
        {
          text: this.$t('dating.selectFromVideo'),
          code: "video",
        },
      ],
      picFeeName: 'jy.album.platform',
      picFee: null,
      fileListIndex: 1,
      // fee: 1,
      currencys: [],
      currencyList:[],
      fileList: [],
      setPrice: "",
      selectReceiptCurrency: [],
      receiptCurrency: "",
      show: false,
      applyFileJson: [],
      fileList1: {},
      fileList2: {},
      fileList3: {},
      fileList4: {},
      fileList5: {},
      fileList6: {},
      fileList7: {},
      fileList8: {},
      fileList9: {},
    };
  },
  computed: {
    fileNum() {
      let num = 0;
      for (let i = 1; i < 10; i++) {
        if (Object.keys(this[`fileList${i}`]).length > 0) {
          num++;
        }
      }
      return num;
    },
  },
  methods: {
    async getFeePercent (feeName, type) {
      const resp = await queryFeePercent(feeName)
      if (resp.result.code === 200) {
        if (type === 'chat') {
          this.chatFee = resp.result.msg * 100
        } else if (type === 'pic') {
          this.picFee = resp.result.msg * 100
        }
      }
    },
    handleOpenPicker(){
      this.show = true;
      console.log('currencyList----------->', this.currencyList);
    },
    async backFill() {
      if (this.type == 1) {
        console.log(this.formData.userImagePayList);
        if (this.formData.userImagePayList.length > 0) {
          this.formData.userImagePayList.forEach((item, index) => {
            this[`fileList${index + 1}`] = {
              url: item.imageUrl,
              compressImage: item.imageUrlCompress || item.imageUrl,
              oneUrl: item.imageUrlCompress,
              fileType: item.type == 0 ? "image" : "video",
            };
          });
        }
        this.setPrice = this.formData.jyUserAlbumPay.price;
        this.receiptCurrency = this.formData.jyUserAlbumPay.currency;
        this.selectReceiptCurrency = [
          {
            id: this.formData.jyUserAlbumPay.currencyId,
            currency: this.formData.jyUserAlbumPay.currency,
          },
        ];
        this.chatUnit = await getSymbol(this.selectReceiptCurrency[0].id);
      } else {
        if (this.formData.userImageList.length > 0) {
          this.formData.userImageList.forEach((item, index) => {
            this[`fileList${index + 1}`] = {
              url: item.imageUrl,
              compressImage: item.imageUrlCompress || item.imageUrl,
              oneUrl: item.imageUrlCompress || item.imageUrl,
              fileType: item.type == 0 ? "image" : "video",
            };
          });
        }
      }
    },
    onTypePop(index) {
      this.fileListIndex = index;
      this.SelectPopupShow = true;
    },
    clearFile(index) {
      this[`fileList${index}`] = {};
    },
    //预览
    showPreview(url) {
      uni.previewImage({
        urls: [url],
      });
    },
    // 选择照片或视频
    onSelectType(type) {
      switch (type) {
        case "video":
          this.handleUploadVideo();
          break;
        case "image":
          this.handleUploadImage();
          break;
        default:
          break;
      }
    },
    async handleUploadImage() {
      console.log("上传图片", this.fileListIndex);
      uni.chooseImage({
        count: 1,
        sourceType: ["camera", "album"],
        success: async (res) => {
          console.log(res);
          if (res.tempFiles[0].size > 5 * 1024 * 1024) {
            uni.showToast({
              title: this.$t("dating.picLimit", {value: 5}),
              icon: "none",
            });
            return;
          }
          uni.showLoading()
          const result = await this.uploadFilePromise(res.tempFilePaths[0]);
          uni.hideLoading()
          console.log(result);
          this[`fileList${this.fileListIndex}`] = {
            ...result,
            fileType: "image",
          };
        },
      });
    },
    async handleUploadVideo() {
      console.log("上传视频");
      uni.chooseVideo({
        maxDuration: 60,
        count: 1,
        sourceType: ["camera", "album"],
        success: async (res) => {
          console.log(res);
          if (res.size > 10 * 1024 * 1024) {
            uni.showToast({
              title: this.$t("dating.videoLimit", {value: 10}),
              icon: "none",
            });
            return;
          }
          uni.showLoading()
          const result = await this.uploadFilePromise(res.tempFilePath);
          uni.hideLoading()
          this[`fileList${this.fileListIndex}`] = {
            ...result,
            fileType: "video",
          };
        },
      });
    },
    close() {
      this.show = false;
    },
    async confirm( value ) {
      console.log('value',value);
      const arr = this.currencyList.filter(i=>{
        return i.id == value
      })
      console.log('arr',arr);
      this.selectReceiptCurrency = arr;
      console.log('selectReceiptCurrency', this.selectReceiptCurrency);
      
      console.log('arr',arr.currency);
      this.receiptCurrency = this.selectReceiptCurrency[0].currency;
      this.show = false;
      this.chatUnit = await getSymbol(this.selectReceiptCurrency[0].id);
    },
    async getCurrency() {
      const {
				success,
				result
			} = await getWalletList()
      if (success) {
				this.currencyList = result.rows.filter(i => {
          i.currency = i.currencyVo.currency
          i.id = i.currencyVo.id
					return i.currencyVo.isOpen == 1
				})
			
		
			}
      console.log('currencyList',this.currencyList);
    },
    //提交审核
    async postHandle() {
      console.log(this.formData);
      let isPost = 0; //判断是否存在图片，至少为1通过
      let postList = []; //存放九宫格图片视频数组
      //循环九次，格子中存在图片或视频，存放进数组
      for (let i = 1; i < 10; i++) {
        if (Object.keys(this[`fileList${i}`]).length > 0) {
          console.log(this[`fileList${i}`]);
          postList.push({
            imageUrl: this[`fileList${i}`].url,
            imageUrlCompress: this[`fileList${i}`].fileType == "video"
                ? this[`fileList${i}`].oneUrl
                : this[`fileList${i}`].compressImage || this[`fileList${i}`].url,
            imageUrlIndex: this[`fileList${i}`].url,
            type: this[`fileList${i}`].fileType == "image" ? 0 : 1,
          });
          isPost = 1;
        }
      }
      // if (!isPost) {
      //   uni.showToast({
      //     title: "请选择资源",
      //     icon: "error",
      //   });
      //   return;
      // }
      let jyUserAlbum = {
        imageUrl: postList && postList.length > 0 ? postList[0].imageUrl : null,
        imageUrlCompress: postList && postList.length > 0 ? postList[0].imageUrlCompress : null,
        isPay: this.type ? (postList && postList.length > 0 ? 1 : 0) : 0,
        price: this.type ? this.setPrice : null,
        currencyId: this.type ? this.selectReceiptCurrency[0].id : null,
        currency: this.type ? this.selectReceiptCurrency[0].currency : null,
      };
      let k1, k2;
      if (this.type) {
        k1 = "jyUserAlbumPay";
        k2 = "userImagePayList";
      } else {
        k1 = "jyUserAlbum";
        k2 = "userImageList";
      }
      const obj = {
        [k1]: jyUserAlbum,
        [k2]: postList,
      };
      if (this.formData.userPersonalsId) {
        this.getPeopleUpdate(obj)
      } else {
        this.getPeopleAdd(obj)
      }
    },
    // 返回上一页
		gotoBack() {
			uni.redirectTo({
				url: '/pagesDiscover/friendsInformation/FriendsInformation'
			});
		},
    async getPeopleAdd (obj) {
      const resp = await friendInfoAdd({
        ...this.formData,
        ...obj,
      })
      if (resp.result.code == 200) {
        this.gotoBack()
      }
    },
    async getPeopleUpdate (obj) {
      const resp = await updateFriendInfo({
        ...this.formData,
        ...obj,
      })
      if (resp.result.code == 200) {
        this.gotoBack()
      }
    },

    //图片路径
    getfileList(index) {
      if (this[`fileList${index}`].fileType == "video") {
        return { ...this[`fileList${index}`], type: "video" };
      } else if (this[`fileList${index}`].fileType == "image") {
        return { ...this[`fileList${index}`], type: "image" };
      } else {
        return null;
      }
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
      this.applyFileJson.splice(event.index, 1);
    },
    async beforeRead(event) {
      console.log(event);
    },
    //读取获取之后的信息
    async afterRead(event) {
      console.log(event);
      console.log(this[`fileList${event.name}`]);
      console.log(event.file);
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      console.log(lists, "图片对象");
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url);
        let item = this[`fileList${event.name}`][fileListLen];
        console.log(item, "xuneux");
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result,
          })
        );
        fileListLen++;
      }
    },
    //上传路径
    uploadFilePromise(url) {
      console.log(url);
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: config.server + "/app/oss/upload", // 仅为示例，非真实的接口地址
          filePath: url,
          name: "file",
          header: {
            Authorization: `Bearer ${store.state.token}`,
            version: config.version,
          },
          formData: {
            user: "upload",
          },
          success: (res) => {
            const resp = JSON.parse(res.data);
            this.applyFileJson.push(resp.data.url);
            setTimeout(() => {
              resolve(resp.data);
            }, 1000);
          },
        });
      });
    },
  },
  mounted() {
    this.getCurrency().then(()=>{
      this.receiptCurrency = this.currencyList[0].currency;
    });
    console.log('receiptCurrency',  this.receiptCurrency);
  },
  onLoad(option) {
    this.type = JSON.parse(option.type);
    if (this.type) {
      this.getFeePercent(this.picFeeName, 'pic')
    }
    if (option.formData) {
      this.formData = JSON.parse(option.formData);
    } else {
      this.formData = this.$store.state.friendsInformation;
    }
    this.backFill();
    this.getPrePages();
  },
};
</script>

<style lang="scss" scoped>
.photo-view {
  padding: 30upx;
  padding-bottom: 150rpx;
  .label {
    margin-top: 60upx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 17upx;
    .first {
      font-size: 26upx;
      font-weight: 400;
      color: #000000;
    }
    .number {
      font-size: 26upx;
      font-weight: 400;
      color: #878787;
    }
  }
  .limit {
    font-size: 24upx;
    font-weight: 400;
    color: #878787;
    .Mb {
      color: #61bdb2;
    }
  }
    
  .img-photo {
    margin-top: 40upx;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }
  .add {
    width: 32%;
    height: 214upx;
    // margin-right: 18upx;
    margin-bottom: 24upx;
    position: relative;
    .icon {
      z-index: 99;
      position: absolute;
      top: -10upx;
      right: -10upx;
    }
  }
  .price-view {
    padding: 0upx 30upx;
    background: #ffffff;
    border-radius: 20upx;
    margin-top: 30upx;
    .content-detail {
      padding: 40upx 0upx;
      background: #ffffff;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 2upx solid #f6f6f6;
      .detail {
        display: flex;
        align-items: center;
      }
      .arrow-icon {
        color: #a6a6a6;
        font-size: 30upx;
        margin-left: 30upx;
      }
      .danwei {
        font-size: 30upx;
        font-weight: 400;
        color: #000000;
        margin-left: 13upx;
      }
      .input-view {
        text-align: right;
      }
    }
  }
  .btn {
    position: fixed;
    bottom: 20upx;
    width: 90%;
    height: 90upx;
    background: #61bdb2;
    border-radius: 20upx;
    line-height: 90upx;
    text-align: center;
    font-size: 30upx;
    font-weight: 500;
    color: #ffffff;
  }
}
.explain {
  margin-top: 30upx;
  text-align: right;
  font-size: 26upx;
  font-weight: 400;
  color: #878787;
  .money {
    color: #fe6600;
  }
}
</style>
